package com.pear.core.ctl;

import javax.servlet.http.HttpServletRequest;

/**
 * 类<code>IPTools</code>提供了IP相关的功能。
 *
 * @author 顾晓健
 * @version %I%, %G%
 * @since 1.0
 */
public class IPTools {

    /**
     * <p>获取真实的IP地址。</p>
     * <p>获取IP地址过程：先在header头中获取"x-forwarded-for"属性，若为空或者"unknown"，则继续从header中获取"Proxy-Client-IP"属性，
     * 如果还是没有，则获取"WL-Proxy-Client-IP"属性，若依然无法获得，则取请求的远程地址，即getRemoteAddr()返回的IP地址信息。</p>
     *
     * @param request HttpServletRequest对象
     * @return 真实的IP地址
     */
    public static String getIpAddres(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (StringTools.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

}
